import java.io.*;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

public class UserManager 
{		
	private Employee currentEmployee;
	private Vector<Employee> EmployeeList = new Vector<Employee>();
	private String EmployeeName = "User";
	private Employee loadEmployee;
	private int workedtime = 0;
	
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Calendar cal = Calendar.getInstance();
	java.util.Date begin;
	java.util.Date end;
	 long between;
	
		
	//Singleton UserManager
	public UserManager(/*File initFile*/)
	{ 		
		currentEmployee = null;
	}
	 
	// Accessors
	public Employee getCurrentUser(){
		return currentEmployee;
	}
	
	public Vector<Employee> getEmployeeList(){
		return EmployeeList;
	}
				
	public boolean login(String initName, String initPassword){
		String passwordEncrypt = encrypt(initPassword);
		if (loadUsers(initName, passwordEncrypt))
			return true;
		else return false;
	}
	
	// encrypt the password the user entered
	public String encrypt(String initPassword){
		String encrypted = "";
		for (int i=0; i<initPassword.length(); i++){
			int temp = (int)(initPassword.toLowerCase().charAt(i))+1;
			encrypted += (char) temp;
		}
		return encrypted;
	}
	
	public String decrypt(String initPassword){
		String decrypted = "";
		for (int i=0; i<initPassword.length(); i++){
			int temp = (int)(initPassword.toLowerCase().charAt(i))-1;
			decrypted += (char) temp;
		}
		return decrypted;
	}
	
	/** check with the password in the database
	 * if the user exists, then get the current Employee
	 */
	public boolean check(String initName, String encrypted){
		boolean valid = false;
		try{
		    Connection conn=ConnectionUtils.getConnection();
		    Statement stmt=conn.createStatement();
		    ResultSet rs=stmt.executeQuery("select count(*) from reviewer where username='" + initName
		    		+ "'and password='" + encrypted +"'");
		    if(rs.next()){		    	
		    	if(rs.getInt(1)>0){		    		
		    	    valid=true;
		    	    System.out.println("user verified");
		    	    EmployeeName=initName;
		    	}
		    }
		    rs.close();
		    conn.close();		    
		}catch(Exception e){
    		e.printStackTrace();
    	}		
		
		return valid;
	}
		
	// load from database
		public boolean loadUsers(String initName, String encrypted)
		{
			boolean valid = false;
			try{
				Connection conn=ConnectionUtils.getConnection();		
				Statement s=conn.createStatement();
				ResultSet rs=s.executeQuery("select * from employee where username='" + initName
		    		+ "'and password='" + encrypted +"'");
				String reader = null;
				int id= 0;
				String password= "";
				String Username= "";
				boolean manager = false;
				int workTime = 0;
				if(rs.next()){				
					id=rs.getInt(1);
					Username = rs.getString(2);
					Username = new String(Username.getBytes("ISO-8859-1"),"GB2312");        	
					password = rs.getString(3);
					password = new String(password.getBytes("ISO-8859-1"),"GB2312");
					password = decrypt(password);
					reader = rs.getString(4);
					reader = new String(reader.getBytes("ISO-8859-1"),"GB2312");
					if(reader.equals("Yes"))
						manager = true;
					workTime = rs.getInt(5);
					workedtime = workTime;
					begin = df.parse(getStringDate());
					
					currentEmployee = new Employee(id,Username,password,manager,workTime);
					//System.out.println(id+Username+password+manager+workTime);
					if(currentEmployee!=null)
					EmployeeList.add(currentEmployee);
					valid = true;
					System.out.println("user verified");
					rs.close();
					
					PreparedStatement ss=conn.prepareStatement("select * from employee",
		                    ResultSet.TYPE_SCROLL_SENSITIVE,
		                    ResultSet.CONCUR_UPDATABLE);
		    	    ResultSet rss=ss.executeQuery();
		    	    reader = null;
		            while(rss.next()){
		            		if(currentEmployee.getid()==rss.getInt(1)){      			
		            		}
		            		else{
		            			id=rss.getInt(1);
		    					Username = rss.getString(2);
		    					Username = new String(Username.getBytes("ISO-8859-1"),"GB2312");        	
		    					password = rss.getString(3);
		    					password = new String(password.getBytes("ISO-8859-1"),"GB2312");
		    					password = decrypt(password);
		    					reader = rss.getString(4);
		    					reader = new String(reader.getBytes("ISO-8859-1"),"GB2312");
		    					if(reader.equals("Yes"))
		    						manager = true;
		    					workTime = rss.getInt(5);
		            			loadEmployee= new Employee(id,Username,password,manager,workTime);
		            			EmployeeList.add(loadEmployee);
		            			System.out.println("+1");
		            		}		            		
		            	}
		            	System.out.println("all users information are loaded");
		            rss.close();
		            conn.close();
				}			           
			}catch(Exception e){
	    		e.printStackTrace();
	    	}
			return valid; 
		}
		// update user info
		public void updateUser(Employee e){
			for (int i=0; i<EmployeeList.size(); i++)
				if (EmployeeList.get(i).getid()==e.getid())
					EmployeeList.set(i, e);
			try{
			    Connection conn=ConnectionUtils.getConnection();
			    PreparedStatement s=conn.prepareStatement("select count(*) from employee where id= ?");
			    s.setInt(1, e.getid());
			    ResultSet rs = s.executeQuery();
			    if(rs.next()){
			    	if(rs.getInt(1)>0){				  
			    		rs.close();
			    		PreparedStatement ss=conn.prepareStatement("DELETE from employee where id= ?");
			    		ss.setInt(1, e.getid());
			    		int deletecount = ss.executeUpdate();
			    		System.out.println(deletecount + " row of user data is updated");
			    	}				    	    
			    }
		    
			    if(currentEmployee.getid()==e.getid()){
			    	end = df.parse(getStringDate());
			    	long diff = end.getTime() - begin.getTime() ;
			        long min = diff / (1000 * 60  );
			        int addTime = (int)min;
			        currentEmployee.setworkTime(currentEmployee.getworktime()+addTime);
			    }
			    conn.setAutoCommit(false);
			    PreparedStatement stmt = conn.prepareStatement("INSERT INTO employee VALUES ( ?,?,?,?,?)");
		        
		        stmt.setInt(1,  e.getid());
		        stmt.setString(2,  e.getName());
		        boolean managerCheck=e.getmanagerCheck();
		        if(managerCheck=true)
		        	stmt.setString(4,  "Yes");
		        else stmt.setString(4,  "No");
		        stmt.setString(3,  encrypt(e.getPassword()));
		        stmt.setInt(5,  e.getworktime());			        	
		    
		    stmt.addBatch();
	        int[] updateCounts = stmt.executeBatch();
	        conn.commit(); 
	        conn.close();
			}catch(Exception ee){
	    		ee.printStackTrace();
	    	}	
		}
		public static String getStringDate() {
		       Date currentTime = new Date();
		       SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		       String dateString = formatter.format(currentTime);
		       return dateString;
		}
	
}
